package io.gitee.chearnee.fw.dingtalk.manager;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.taobao.api.TaobaoResponse;
import io.gitee.chearnee.fw.dingtalk.enums.AppType;
import io.gitee.chearnee.fw.dingtalk.util.DingTalkUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2021/7/28 21:27
 */
@Slf4j
public abstract class DingTalk implements AutoCloseable {

  protected AppType appType;
  protected final ThreadLocal<String> dingTalkNameThreadLocal = new NamedThreadLocal<>(
          "dingTalk-name");

  protected DingTalk(AppType appType) {
    this.appType = appType;
  }

  /**
   * choose dingTalk
   */
  public DingTalk setDingTalkName(String dingTalkName) {
    dingTalkNameThreadLocal.set(dingTalkName);
    return this;
  }

  @Autowired
  protected DingTalkUtil dingTalkUtil;

  protected DingTalkClient dingTalkClient(AppType appType, String businessUri) {
    return new DefaultDingTalkClient(
            dingTalkUtil
                    .buildRequestUrl(appType.getUrl() + businessUri, null, dingTalkNameThreadLocal.get()));
  }


  protected abstract DingTalkClient getClient(String businessUri);


  @SneakyThrows
  protected <T extends TaobaoResponse> T sendResponse(T response) {
    if (!response.isSuccess()) {
      log.warn("发送钉钉消息失败:errcode:{},errmsg:{}", response.getErrorCode(), response.getMsg());
    }
    return response;
  }

  @Override
  public void close() {
    dingTalkNameThreadLocal.remove();
  }
}
